package com.dynamic.data.source.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.boot.autoconfigure.MybatisProperties;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.env.Environment;
import org.springframework.core.io.ResourceLoader;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.Properties;

/**
 * 开发公司：联信
 * 版权：联信
 * <p>
 * Annotation
 *
 * @author 刘志强
 * @created Create Time: 2021/2/2
 */
@Configuration
public class MybatisConfig {

    private final Environment env;

    @Value("${spring.datasource.url}")
    private String url;
    @Value("${spring.datasource.username}")
    private String username;
    @Value("${spring.datasource.password}")
    private String password;

    public MybatisConfig(Environment env) {
        this.env = env;
    }

    @Bean(name = "defaultDataSource")
    public DataSource defaultDataSource(@Qualifier("poolProperties") Properties poolProperties) throws SQLException {
        DruidDataSource dataSource = DataSourceBuilder.create()
                // 数据库 连接池类型 如果不设置类型默认类型为 com.zaxxer.hikari.HikariDataSource
                .type(DruidDataSource.class)
                // 驱动
                .driverClassName("com.mysql.cj.jdbc.Driver")
                // 链接
                .url(url)
                // 账号
                .username(username)
                // 密码
                .password(password)
                .build();
        // 加载连接池配置信息
        dataSource.configFromPropety(poolProperties);
        // 初始化
        dataSource.init();
        // 初始化
        DataSourceAdmin.dataSourceMap.put("default",dataSource);
        return dataSource;
    }

    /**
     * 创建数据源路由
     *
     * @return
     */
    @Bean("dynamicDataSource")
    public DataSource dynamicDataSource() throws SQLException {
        DynamicDataSource dynamicDataSource = new DynamicDataSource();
        dynamicDataSource.setDefaultDataSource(defaultDataSource(poolProperties()));
        dynamicDataSource.setDefaultTargetDataSource(defaultDataSource(poolProperties()));
        dynamicDataSource.setDataSources(DataSourceAdmin.dataSourceMap);
        return dynamicDataSource;
    }


    @Bean(name = "sqlSessionFactory")
    @Primary
    public SqlSessionFactory sqlSessionFactory(
            @Qualifier("dynamicDataSource") DataSource dynamicDataSource,
            @Qualifier("mybatisData") MybatisProperties properties,
            ResourceLoader resourceLoader) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dynamicDataSource);
        bean.setTypeAliasesPackage(properties.getTypeAliasesPackage());
        bean.setConfigLocation(resourceLoader.getResource(properties.getConfigLocation()));
        bean.setMapperLocations(properties.resolveMapperLocations());
        return bean.getObject();
    }

    @Bean(name = "sqlSessionTemplate")
    @Primary
    public SqlSessionTemplate sqlSessionTemplate(
            @Qualifier("sqlSessionFactory") SqlSessionFactory sqlSessionFactory
    ) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

    @Bean(name = "mybatisData")
    @ConfigurationProperties(prefix = "mybatis")
    @Primary
    public MybatisProperties mybatisProperties() {
        MybatisProperties mybatisProperties = new MybatisProperties();
        return mybatisProperties;
    }

    /**
     * 事务处理器
     * @param dynamicDataSource
     * @return
     */
    @Bean(name = "dataSourceTransactionManager")
    @Primary
    public DataSourceTransactionManager dataSourceTransactionManager(@Qualifier("dynamicDataSource") DataSource dynamicDataSource) {
        return new DataSourceTransactionManager(dynamicDataSource);
    }

    @Bean("poolProperties")
    public Properties poolProperties() {
        String prefixPool = "spring.datasource.pool.";
        Properties prop = new Properties();
        prop.put("druid.initialSize", env.getProperty(prefixPool + "initialSize", String.class));
        prop.put("druid.maxActive", env.getProperty(prefixPool + "maxActive", String.class));
        prop.put("druid.minIdle", env.getProperty(prefixPool + "minIdle", String.class));
        prop.put("druid.maxWait", env.getProperty(prefixPool + "maxWait", String.class));
        prop.put("druid.poolPreparedStatements", env.getProperty(prefixPool + "poolPreparedStatements", String.class));
        prop.put("druid.maxPoolPreparedStatementPerConnectionSize", env.getProperty(prefixPool + "maxPoolPreparedStatementPerConnectionSize", String.class));
        prop.put("druid.validationQuery", env.getProperty(prefixPool + "validationQuery", String.class));
        prop.put("druid.validationQueryTimeout", env.getProperty(prefixPool + "validationQueryTimeout", String.class));
        prop.put("druid.testOnBorrow", env.getProperty(prefixPool + "testOnBorrow", String.class));
        prop.put("druid.testOnReturn", env.getProperty(prefixPool + "testOnReturn", String.class));
        prop.put("druid.testWhileIdle", env.getProperty(prefixPool + "testWhileIdle", String.class));
        prop.put("druid.timeBetweenEvictionRunsMillis", env.getProperty(prefixPool + "timeBetweenEvictionRunsMillis", String.class));
        prop.put("druid.minEvictableIdleTimeMillis", env.getProperty(prefixPool + "minEvictableIdleTimeMillis", String.class));
        prop.put("druid.filters", env.getProperty(prefixPool + "filters", String.class));
        return prop;
    }
}
